local Image = require "widgets/image"

local function log(...)
    SUGAR_webber_the_trainer:declare(...)
end

---comment
---@param bar widget_inventorybar|widget_containerwidget
---@param items ent[]|nil
local function hightinv(bar,items,prefabid)
    if items then
        ---@type widget_image[]|nil
        local frames = {}
        local found = false
        for k,v in pairs(items) do
            if v.prefab == prefabid then
                found = true
                if bar.inv and bar.inv[k] then
                    local frame = bar.inv[k]:AddChild(Image('images/hud.xml','slot_select.tex','slot_select.tex'))
                    table.insert(frames or {},frame)
                    frame:SetSize(83,83)
                end
            end
        end
        if found then
            SUGAR_webber_the_trainer:taskDoPeriodicForAWhile(nil,nil,.5,2,function ()
                for _,v in pairs(frames or {}) do
                    if v.shown then
                        v:Hide()
                    else
                        v:Show()
                    end
                end
            end,function ()
                for _,v in pairs(frames or {}) do
                    if v then
                        v:Kill()
                    end
                end
                frames = nil
            end)
        end
    end
end

AddClassPostConstruct('widgets/inventorybar',
---@param self widget_inventorybar
function (self, ...)
    local bar = self
    if ThePlayer then
        ThePlayer:ListenForEvent('webbert_find_staff_ininv',function ()
            local items = ThePlayer.replica.inventory:GetItems()
            if items then
                hightinv(bar,items,'staff_arachnidnexus')
            end
        end)
    end
end)

AddClassPostConstruct('widgets/containerwidget',
---@param self widget_containerwidget
function (self, ...)
    local bar = self
    if ThePlayer then
        ThePlayer:ListenForEvent('webbert_find_staff_ininv',function ()
            local items = bar.container and bar.container.replica.inventoryitem and bar.container.replica.inventoryitem:IsGrandOwner(ThePlayer) and bar.container.replica.container:GetItems() or nil
            if items then
                hightinv(bar,items,'staff_arachnidnexus')
            end
        end)
    end
end)